<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use addons\epay\library\Service as EpayService;
use EasyWeChat\Foundation\Application as WXPAY_APP;
use EasyWeChat\Payment\Order as WXPAY_ORDER;
use addons\third\model\Third;
use think\Config;


/**
 * 个人中心接口
 */
class My extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $this->user_id = $this->auth->id;
        // $this->user_id = 1;
    }  


    /**
     * 我的维修订单
     */
    public function my_repair(){
        $my_repair = Db::name('repair')->alias('r')->field("r.*,l.goods_name,FROM_UNIXTIME(r.createtime,'%Y-%m-%d %H:%i:%s') as createtime,FROM_UNIXTIME(r.updatetime,'%Y-%m-%d %H:%i:%s') as updatetime")->join('litestore_goods l','r.goods_id=l.goods_id')->where(['r.user_id'=>$this->user_id])->order('r.weigh desc')->select();

        $this->success('我的维修订单',$my_repair);
    }

    /**
     * 我的回收订单
     */
    public function my_recovery(){
        $my_recovery = Db::name('recovery')->field("*,FROM_UNIXTIME(createtime,'%Y-%m-%d %H:%i:%s') as createtime,FROM_UNIXTIME(updatetime,'%Y-%m-%d %H:%i:%s') as updatetime")->where(['user_id'=>$this->user_id])->order('weigh desc')->select();
        $this->success('我的回收订单',$my_recovery);
    }

    /**
     * 我的订单列表 spec_type等于30是多个商品的订单情况，会有个goods_list数组。order_status订单状态:10=未支付,20=已支付待发货,30=已发货,40=确认收货
     */
    public function my_order_list(){
        $my_order_list = Db::name('order')->field("*,FROM_UNIXTIME(createtime,'%Y-%m-%d %H:%i:%s') as createtime,FROM_UNIXTIME(updatetime,'%Y-%m-%d %H:%i:%s') as updatetime")->where(['user_id'=>$this->user_id])->order('updatetime desc')->select();
        foreach ($my_order_list as $key => $value) {
            if(!empty($value['shoppingcar_id'])){
                $array_shoppingid = json_decode($value['shoppingcar_id'],true);
                $shoppingcar_data = Db::name('shoppingcar')->where('id','in',$array_shoppingid)->select();
                $my_order_list[$key]['goods_list'] = $shoppingcar_data;
            }
        }
        $this->success('我的订单列表',$my_order_list);
    }

    /**
     * 我的订单详情 。track_number:快递单号。company快递公司。还带上收货地址
     * @param int $order_id 订单id
     */
    public function my_order_detail(){

        $my_order_detail = Db::name('order')->alias('o')->field("o.*,FROM_UNIXTIME(o.createtime,'%Y-%m-%d %H:%i:%s') as createtime,a.phone,a.name,a.province,a.region,a.city,a.detail")->join('address a','o.address_id=a.id')->where(['o.id'=>input('order_id')])->find();

        if($my_order_detail['shoppingcar_id']){
            $array_shoppingid = json_decode($my_order_detail['shoppingcar_id'],true);
            $shoppingcar_data = Db::name('shoppingcar')->where('id','in',$array_shoppingid)->select();
            $my_order_detail['goods_list'] = $shoppingcar_data;
        }
        $this->success('我的订单列表',$my_order_detail);
    }

    /**
     * 未支付订单进行支付
     * @param int $order_id 订单id
     */
    public function order_pay(){
        $order_id = input('order_id');
        $order_detail = Db::name('order')->where('id',$order_id)->find();

        if($order_detail){

            // 发起微信支付
            $this->init_wx_pay_for_wxapp();
         
            $third = Third::where(['user_id' => $this->user_id, 'platform' => 'wxapp'])->find();
        
            $payment = $this->wxapp->payment;
            $attributes = [
                'trade_type'       => 'JSAPI',
                'body'             => Config::get('site.name'),
                'detail'           => Config::get('site.name'),
                'out_trade_no'     => $order_detail['order_no'],
                'openid'           => $third['openid'],
                'total_fee'        => $order_detail['total_price']*100,
                'notify_url'       => Config::get('site.cdnurl').'api/order/callback_for_wxapp',
            ];
            $order_pay = new WXPAY_ORDER($attributes);
            $result = $payment->prepare($order_pay);
            if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
                $prepayId = $result->prepay_id;
                $config = $payment->configForJSSDKPayment($prepayId); // 返回数组
                return $this->success('订单创建成功,预支付成功',$config);
            }
            return $this->error('微信支付调用失败',$result);
        }else{
            $this->error('订单失效');
        }

    }

    private function init_wx_pay_for_wxapp(){
        $config = get_addon_config('epay');
        $options = [
            'debug'  => true,
            'log' => [
                'level' => 'debug',
                'file'  => LOG_PATH . '/tmp/easywechat.log',
            ],
            'app_id'   => $config['wechat']['miniapp_id'],// 小程序 APPID
            'secret'   => $config['wechat']['app_secret'],//小程序密钥
            'payment' => [
                'merchant_id'        =>  $config['wechat']['mch_id'],//小程序商户号
                'key'                =>  $config['wechat']['key'],//小程序支付密钥
                'notify_url'         =>  \think\Request::instance()->domain().'/api/order/callback_for_wxapp',
            ],

        ];
        $this->wxapp = new WXPAY_APP($options);
    }




}
